package com.violet.utils;

import com.violet.properties.FileUploadProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Component
@RequiredArgsConstructor
public class FileUtils {

    private final FileUploadProperties properties;
    private final ExecutorUtils executor;

    private void verifyImage(MultipartFile file) {
        if (file == null)
            throw new RuntimeException("文件为空");
        // 校验文件类型
        if (!Objects.requireNonNull(file.getContentType()).startsWith("image/"))
            throw new RuntimeException("文件类型错误");
        // 校验文件大小
        if (file.getSize() / (1024d * 1024d) > properties.getImage().maxSize())
            throw new RuntimeException("文件过大");
    }

    private String getFileName(String originalFileName) {
        return UUID.randomUUID() + "." +
                originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
    }

    private void saveImage(MultipartFile file, String fileName) {
        try (
                InputStream inputStream =
                        new BufferedInputStream(file.getInputStream());
                OutputStream outputStream =
                        new BufferedOutputStream(new FileOutputStream(properties.getImage().path() + "/" + fileName))
        ) {
            FileCopyUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败");
        }
    }

    // TODO: 删除图片文件
    public void deleteImage(String fileName) {
        if ("user.jpg".equals(fileName)) return;

        executor.getExecutor().execute(() -> {
            File file = new File(properties.getImage().path() + "/" + fileName);
            if (file.exists()) file.delete();
        });
    }

    // TODO: 保存图片文件
    public String uploadImage(MultipartFile file) {
        verifyImage(file);
        String fileName = getFileName(Objects.requireNonNull(file.getOriginalFilename()));
        executor.getExecutor().execute(() -> saveImage(file, fileName));
        return fileName;
    }

}
